﻿using AntDesign;
using AntDesign.Core.Extensions;
using Blazored.LocalStorage;
using daonaite.Model;
using Microsoft.AspNetCore.Components;
using System.Net.Http;
using System.Net.Http.Json;

namespace daonaite.ui.Util
{
    public class HttpHelp
    {
        /// <summary>
        /// 缓存
        /// </summary>
        private readonly ILocalStorageService localStorage;
        /// <summary>
        /// 请求
        /// </summary>
        private readonly HttpClient httpClient;

        private readonly IMessageService _message;
        private readonly NavigationManager NavigationManager;

        public HttpHelp(ILocalStorageService localStorage, HttpClient _httpClient, IMessageService message, NavigationManager navigationManager)
        {
            this.localStorage = localStorage;
            this.httpClient = _httpClient;
            _message = message;
            NavigationManager = navigationManager;
        }

        /// <summary>
        /// 设置token
        /// </summary>
        public async Task setToken()
        {
            string tk = await localStorage.GetItemAsStringAsync("token");
            if (tk != null)
            {
                httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", tk);
            }
        }

        /// <summary>
        /// 参数拼接
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <returns></returns>
        private string parameterStitching<T>(T data)
        {
            string param = "";

            var tp = data.GetType();
            if (tp.Name == "string")
            {
                param = data.ToString();
            }
            else
            {
                var filds = tp.GetProperties();
                for (int i = 0; i < filds.Length; i++)
                {
                    if (param != "")
                    {
                        param += "&";
                    }
                    param += $"{filds[i].Name}={filds[i].GetValue(data)}";
                }
            }

            return param;
        }


        private async Task<ApiResult<T>?> disposeMessage<T>(HttpResponseMessage message)
        {
            var result = new ApiResult<T>();

            switch (message.StatusCode)
            {
                case System.Net.HttpStatusCode.OK: //请求成功
                    {
                        result = await message.Content.ReadFromJsonAsync<ApiResult<T>>();
                        if (result.Code != 200)
                        {
                            _message.Error($"请求失败:{result.Message}");
                        }
                        break;
                    }
                case System.Net.HttpStatusCode.Unauthorized: //未认证
                    {
                        await localStorage.RemoveItemAsync("token");
                        NavigationManager.NavigateTo("/");
                        break;
                    }
                default: //请求失败
                    {
                        _message.Error($"请求失败:{message.StatusCode.ToString()}");
                        break;
                    }
            }

            return result;
        }


        /// <summary>
        /// get请求
        /// </summary>
        /// <typeparam name="T">返回的数据类型</typeparam>
        /// <typeparam name="T1">参数支持对象与拼接好的字符串</typeparam>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<ApiResult<T>?> getAsync<T, T1>(string url, T1 data)
        {
            ApiResult<T>? result = new ApiResult<T>();
            try
            {
                await setToken();
                // 参数拼接
                string param = parameterStitching(data);

                if (!string.IsNullOrEmpty(param))
                {
                    url = $"{url}?{param}";
                }

                HttpResponseMessage rm = await httpClient.GetAsync(url);
                result = await disposeMessage<T>(rm);

            }
            catch (Exception ex)
            {
                _message.Error($"请求异常:{ex.Message}");
            }
            return result;

        }

        /// <summary>
        /// get请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="T1"></typeparam>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<ApiResult<T>?> getAsync<T>(string url)
        {
            ApiResult<T>? result = new ApiResult<T>();
            try
            {
                await setToken();
                HttpResponseMessage rm = await httpClient.GetAsync(url);
                result = await disposeMessage<T>(rm);
            }
            catch (Exception ex)
            {
                _message.Error($"请求异常:{ex.Message}");
            }

            return result;
        }

        /// <summary>
        /// post请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="T1"></typeparam>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<ApiResult<T>?> posttAsync<T, T1>(string url, T1 data)
        {
            ApiResult<T>? result = new ApiResult<T>();
            try
            {
                await setToken();
                HttpResponseMessage rm = await httpClient.PostAsJsonAsync<T1>(url, data);
                result = await disposeMessage<T>(rm);
            }
            catch (Exception ex)
            {
                _message.Error($"请求异常:{ex.Message}");
            }

            return result;
        }


    }
}
